<template>
  <Layout desc="封装一个动态表单生成器">
    <div class="mt-40 w-100">
      <!-- <FormBuilder ref="formRef" :formItems :rules v-model="formData">
        <template #age>
          <div>这是年龄插槽</div>
        </template>
      </FormBuilder> -->
      <FormBuilder />
      <el-button class="w-full" type="primary" @click="onSubmit"
        >提交</el-button
      >
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { useForm } from '@/hooks/useForm'
import Custom from './components/Custom.vue'

const title = ref('')

const formData = ref({
  name: '',
  age: 0,
  gender: ''
})

const formItems = computed(() => {
  return [
    {
      label: '标题',
      type: Custom,
      span: 12,
      title: title.value
    },
    {
      label: '姓名',
      prop: 'name',
      placeholder: '请输入姓名',
      onChange: (val: string) => {
        title.value = val
      }
    },
    {
      label: '年龄',
      prop: 'age',
      type: 'number'
    },
    {
      label: '性别',
      prop: 'gender',
      type: 'select',
      hidden: true,
      options: ['男', '女'].map(item => ({
        label: item,
        value: item
      }))
    }
  ]
})

const rules = ref({
  name: [
    {
      required: true,
      message: '请输入姓名',
      trigger: 'blur'
    }
  ],
  age: [
    {
      required: true,
      message: '请输入年龄',
      trigger: 'blur'
    }
  ]
})

// const formInstance = useTemplateRef('formRef')

// const onSubmit = async () => {
//   const res = await formInstance.value?.validate()
//   if (!res) return

//   console.log(formData.value)
// }

const { FormBuilder, validate } = useForm({
  modelValue: formData,
  formItems,
  rules
})

const onSubmit = async () => {
  const res = await validate()
  if (!res) return
  console.log(formData.value)
}
</script>

<style scoped lang="scss"></style>
